package org.xxpay.pay.channel.huanyukeji;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.sign.CertDescriptor;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.sign.encrypt.Base64;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.rmi.server.UID;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

@Service
public class HuanyukejiPaymentService extends BasePayment {
    private final static String logPrefix = "【环宇支付】";
    @Override
    public String getChannelName() {
        return HuanyukejiConfig.CHANNEL_NAME;
    }


    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder) {
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
        HuanyukejiConfig config = new HuanyukejiConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("merId", config.getAppId());
        params.put("orderId",payOrder.getPayOrderId());
        params.put("nonceStr", getRandomString(32));
        params.put("sign", getSign(params, config));
        _log.info("{}订单查询请求数据:{}", getChannelName(), JSON.toJSONString(params));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+HuanyukejiConfig.REQ_PAY_QUERY_URL_FIXX, params, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("code"), "1")) {
            String payStatus = origin.getString("status");
            if(StringUtils.equals(payStatus,"1")){
                //支付成功
                retObj.put("status",2);
            }else{
                //支付中
                retObj.put("status",1);
            }
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("sysOrderId"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }

    //下单实现
    private JSONObject doOrderReq(PayOrder payOrder){
        HuanyukejiConfig config = new HuanyukejiConfig(getPayParam(payOrder));
        Map<String,Object> params = Maps.newHashMap();
        //设置参数
        setParams(payOrder,config,config.getPayMode(),params);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));
        //将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+HuanyukejiConfig.REQ_PAY_URL_FIXX, params, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();

        if(StringUtils.equals(origin.getString("code"),"1")){
            JSONObject data = JSONObject.parseObject(origin.getString("data"));
            return buildPayResultOfForm(retObj, payOrder,"<script type=\"text/javascript\">\n" +
                    "　　window.location.href=\""+ data.getString("payurl")+"\";\n" +
                    "　　</script>" );
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.toJSONString());
        return retObj;
    }

    //设置请求主体参数
    private void setParams(PayOrder payOrder, HuanyukejiConfig config,String payMode,Map<String,Object> map){

        map.put("merId", config.getAppId());
        map.put("orderId",payOrder.getPayOrderId());
        map.put("orderAmt", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        map.put("channel", payMode);
        map.put("desc", payOrder.getPayOrderId());
        map.put("ip", payOrder.getClientIp());
        map.put("notifyUrl", payConfig.getNotifyUrl(getChannelName()));
        map.put("returnUrl", payOrder.getReturnUrl());
        map.put("nonceStr",getRandomString(32));
        map.put("sign", getSign(map, config));
    }

    /**
     * 获取签名字符串
     * **/
    private String getSign(Map<String, Object> parameters, HuanyukejiConfig config) {
        String signTxt = SignUtils.parameterText(parameters);
        _log.info("{}加密前字符串：{}", logPrefix, signTxt+"&key="+config.getPrivateStorePathPwd());
        String signValue = SignUtils.MD5.createSign(signTxt, "&key="+config.getPrivateStorePathPwd(), SignUtils.CHARSET_UTF8).toUpperCase();
        _log.info("{}签名前字符串：{}", logPrefix, signValue);
        String sign = SignUtils.RSA2.createSign(signValue, config.getPrivateKey(), SignUtils.CHARSET_UTF8);
        _log.info("{}签名后Sign值：{}", logPrefix, sign);
        return sign;
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    private static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
